import frappe
from frappe.utils import make_random

def apply_make_random_patches():
    """应用随机查询的达梦数据库补丁"""
    
    # 保存原始函数
    original_get_random = make_random.get_random

    def patched_get_random(doctype: str, filters: dict | None = None, doc: bool = False):
        """随机获取文档记录，支持达梦数据库
        
        Args:
            doctype: 文档类型
            filters: 过滤条件
            doc: 是否返回完整文档对象
        """
        if frappe.conf.db_type != "dm":
            return original_get_random(doctype, filters, doc)

        # 构建过滤条件
        condition = []
        if filters:
            condition.extend('"{}"=\'{}\''.format(key, str(val).replace("'", "'")) for key, val in filters.items())
        condition = " where " + " and ".join(condition) if condition else ""

        # 达梦数据库的随机查询
        out = frappe.db.sql(
            f"""SELECT "NAME" 
            FROM "tab{doctype}" {condition}
            ORDER BY DBMS_RANDOM.VALUE() 
            FETCH FIRST 1 ROWS ONLY"""
        )

        out = out and out[0][0] or None

        if doc and out:
            return frappe.get_doc(doctype, out)
        return out

    # 应用补丁
    make_random.get_random = patched_get_random
